<template>
  <a-modal
    :width="modalWidth"
    :visible="visible"
    :title="title"
    :confirm-loading="loading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="取消"
  >
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form-model
          layout="inline"
          ref="myForm"
          :model="form"
          :rules="validatorRules"
          :label-col="{ style: { width: '150px' } }"
        >
          <a-row :gutter="24">
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="提现手续费（%）" prop="withdrawalFee">
                <a-input allowClear class="per100" placeholder="请输入" v-model="form.withdrawalFee" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="订单分成（%）" prop="orderSharding">
                <a-input allowClear class="per100" placeholder="请输入" v-model="form.orderSharding" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="手机号码" prop="phone">
                <a-input allowClear class="per100" placeholder="请输入" v-model="form.phone" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="密码明文" prop="passwordPlaintext">
                <a-input allowClear class="per100" placeholder="请输入" v-model="form.passwordPlaintext" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="姓名" prop="realname">
                <a-input allowClear placeholder="请输入" v-model="form.realname" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="性別" prop="sex">
                <j-dict-select-tag
                  allowClear
                  v-model="form.sex"
                  placeholder="请选择"
                  dictCode="sex"
                  @input="
                    () => {
                      $refs.myForm.validateField('sex')
                    }
                  "
                />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="昵称" prop="nickName">
                <a-input allowClear placeholder="请输入" v-model="form.nickName" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="联系电话">
                <a-input allowClear class="per100" placeholder="请输入" v-model="form.telephone" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="提现方式" prop="withdrawalMethod">
                <j-dict-select-tag
                  allowClear
                  v-model="form.withdrawalMethod"
                  placeholder="请选择"
                  dictCode="withdrawType"
                  @input="
                    () => {
                      $refs.myForm.validateField('withdrawalMethod')
                    }
                  "
                />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="身份证" prop="idCard">
                <a-input allowClear v-model="form.idCard" placeholder="请输入" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="储备金设置" prop="reserveSet">
                <a-input allowClear v-model="form.reserveSet" placeholder="请输入" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="代理商类型" prop="agentType">
                <j-dict-select-tag allowClear v-model="form.agentModel" placeholder="请选择" dictCode="agentModel" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="24" :xl="16">
              <a-form-model-item prop="agentArea" class="my-required">
                <label slot="label"><span style="color:red">*</span> 代理区域</label>
                <a-row :gutter="5" :style="{ 'margin-bottom': 0, 'vertical-align': 'top' }">
                  <a-col :span="6">
                    <a-select
                      placeholder="请选择省"
                      v-model="form.provinceCode"
                      @change="(e, data) => addressChange(e, 'cityOptions', 'province', data.key)"
                    >
                      <a-select-option v-for="item in provinceOptions" :key="item.name" :value="item.code">
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :span="6">
                    <a-select
                      placeholder="请选择市"
                      v-model="form.cityCode"
                      @change="(e, data) => addressChange(e, 'areaOptions', 'city', data.key)"
                    >
                      <a-select-option v-for="item in cityOptions" :key="item.name" :value="item.code">
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :span="6">
                    <a-select
                      placeholder="请选择区"
                      v-model="form.areaCode"
                      @change="(e, data) => addressChange(e, 'streetOptions', 'area', data.key)"
                    >
                      <a-select-option v-for="item in areaOptions" :key="item.name" :value="item.code">
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-col>
                  <a-col :span="6">
                    <a-select
                      placeholder="请选择街道"
                      v-model="form.streetCode"
                      @change="(e, data) => addressChange(e, '', 'street', data.key)"
                    >
                      <a-select-option v-for="item in streetOptions" :key="item.name" :value="item.code">
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </a-col>
                </a-row>
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="加盟日期" prop="joinData">
                <a-date-picker class="per100" v-model="form.joinData" valueFormat="YYYY-MM-DD" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="提现人工审批" prop="withdrawalManualApproval">
                <j-dict-select-tag
                  v-model="form.withdrawalManualApproval"
                  @input="
                    () => {
                      $refs.myForm.validateField('withdrawalManualApproval')
                    }
                  "
                  allowClear
                  placeholder="请选择"
                  dictCode="userWithdrawal"
                />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="控制月提现" prop="controlMonthWithdrawal">
                <a-input
                  allowClear
                  v-model="form.controlMonthWithdrawal"
                  @input="
                    () => {
                      $refs.myForm.validateField('controlMonthWithdrawal')
                    }
                  "
                  placeholder="请输入"
                />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="住址" prop="addressCollect">
                <a-cascader
                  v-model="form.addressCollect"
                  :options="addressOptions"
                  :load-data="loadAddressOnChange"
                  placeholder="请选择"
                  @change="onAddressSelected"
                />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="详细地址" prop="detailAddress">
                <a-input allowClear v-model="form.detailAddress" placeholder="请输入" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="邮编">
                <a-input allowClear v-model="form.postalCode" placeholder="请输入" />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="账户状态" prop="status">
                <j-dict-select-tag
                  allowClear
                  v-model="form.status"
                  @input="
                    () => {
                      $refs.myForm.validateField('status')
                    }
                  "
                  placeholder="请选择"
                  dictCode="status"
                />
              </a-form-model-item>
            </a-col>
            <a-col :sm="24" :md="12" :xl="8">
              <a-form-model-item label="代理商状态" prop="agentStatus">
                <j-dict-select-tag
                  allowClear
                  v-model="form.agentStatus"
                  @input="
                    () => {
                      $refs.myForm.validateField('agentStatus')
                    }
                  "
                  placeholder="请选择"
                  dictCode="agentStatus"
                />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
    </a-card>
  </a-modal>
</template>

<script>
import CommonApi from '@api/Common'
import { getAction, httpAction } from '@api/manage'
import { cloneObject, validateDuplicateValue } from '@/utils/util'
import { AddressChangeMixin } from '@/mixins/AddressChange'

const Api = {
  queryId: '/sys/user/queryById'
}

export default {
  name: 'DeviceAdd',
  mixins: [AddressChangeMixin],
  inject: ['closeCurrent'],
  data() {
    return {
      defaultData: {
        id: 0, // 商家id
        provinceCode: undefined, // 省
        cityCode: undefined, // 市
        areaCode: undefined, // 区
        streetCode: undefined, // 镇
        phone: '', // 手机号
        passwordPlaintext: 'Kcg112233',
        realname: '', // 姓名
        withdrawalManualApproval: '0', //提现人工审批
        sex: 0, // 性别
        nickName: undefined, // 昵称
        agentModel: '1',
        reserveSet: 0, //储备金设置
        joinData: new Date(),
        wechatRealname: '', // 微信实名
        qqNum: '', // QQ号码
        email: '', // 电子邮件EMAIL
        createTime: '', // 创建日期
        lastLoginTime: undefined, // 最后登录时间
        address: undefined, // 地址
        detailAddress: undefined, // 详细地址
        postalCode: undefined, // 邮编
        status: 1, // 账户状态
        agentStatus: '0', // 代理商状态
        delFlag: 0,
        withdrawalMethod: '1', //提现方式
        withdrawalFee: 1,
        orderSharding: 0,
        controlMonthWithdrawal: 50000,
        addressCollect: []
      },
      form: {},
      loading: false,
      visible: false,
      title: '新增代理商',
      modalWidth: '80%',
      provinceOptions: [],
      cityOptions: [],
      areaOptions: [],
      streetOptions: [],
      networkOptions: [],
      validatorRules: {
        withdrawalFee: [{ required: true, message: '提现手续费不能为空', trigger: 'change' }],
        orderSharding: [{ required: true, message: '订单分成不能为空', trigger: 'change' }],
        passwordPlaintext: [{ required: true, message: '密码明文不能为空', trigger: 'change' }],
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'change' },
          {
            validator: this.validatePhone,
            trigger: 'blur'
          },
          {
            validator: (rule, value, callback) =>
              validateDuplicateValue('sys_user', 'phone', value, this.form.id, callback),
            trigger: 'blur'
          }
        ],
        agentArea: [
          {
            validator: (rule, value, callback) => {
              if (['provinceCode', 'cityCode', 'areaCode', 'streetCode'].filter(item => this.form[item]).length === 0) {
                callback('区域不能为空')
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        realname: [{ required: true, message: '姓名不能为空', trigger: 'change' }],
        sex: [{ required: true, message: '性別不能为空', trigger: 'change' }],
        nickName: [{ required: true, message: '昵称不能为空', trigger: 'change' }],
        withdrawalMethod: [{ required: true, message: '提现方式不能为空', trigger: 'change' }],
        idCard: [{ required: true, message: '身份证不能为空', trigger: 'change' }],
        reserveSet: [{ required: true, message: '储备金设置不能为空', trigger: 'change' }],
        agentType: [{ required: true, message: '代理商类型不能为空', trigger: 'change' }],
        joinData: [{ required: true, message: '加盟日期不能为空', trigger: 'change' }],
        withdrawalManualApproval: [{ required: true, message: '提现人工审批不能为空', trigger: 'change' }],
        controlMonthWithdrawal: [{ required: true, message: '控制月提现不能为空', trigger: 'change' }],
        addressCollect: [{ required: true, message: '住址不能为空', trigger: 'change' }],
        detailAddress: [{ required: true, message: '详细地址不能为空', trigger: 'change' }],
        status: [{ required: true, message: '账户状态不能为空', trigger: 'change' }],
        agentStatus: [{ required: true, message: '代理商状态不能为空', trigger: 'change' }]
      }
    }
  },
  async created() {
    // 获取地址
    await this.loadAddressForCascader('addressOptions', {}, true)
    this.getAddress('provinceOptions')
  },
  methods: {
    // 获取地址
    getAddress(name, data) {
      getAction(CommonApi.addressList, data).then(res => {
        this[name] = res.result
      })
    },
    // 地址改变
    addressChange(e, name, key, cn) {
      this.$refs.myForm.validateField('agentArea')
      this.form[`${key}Cn`] = cn
      let obj = {}
      // 改变重置后面市区镇
      if (key === 'province') {
        obj = {
          cityCode: undefined,
          cityCn: undefined,
          areaCode: undefined,
          areaCn: undefined,
          streetCode: undefined,
          streetCn: undefined
        }
        this.cityOptions = []
        this.areaOptions = []
        this.streetOptions = []
      } else if (key === 'city') {
        obj = {
          areaCode: undefined,
          areaCn: undefined,
          streetCode: undefined,
          streetCn: undefined
        }
        this.areaOptions = []
        this.streetOptions = []
      } else if (key === 'area') {
        obj = {
          streetCode: undefined,
          streetCn: undefined
        }
        this.streetOptions = []
      }
      this.form = { ...this.form, ...obj }
      if (name && e) {
        this.getAddress(name, { [`${key}Code`]: e })
      }
    },

    async showModal() {
      this.form = cloneObject(this.defaultData)
      this.form.agentType = '1'
      this.visible = true
    },

    handleCancel() {
      this.visible = false
    },

    handleOk() {
      this.$refs.myForm.validate(valid => {
        if (valid) {
          const url = `/sys/user/add`
          this.loading = true
          const data = Object.assign({}, this.form, {
            username: this.form.phone,
            reserveSet: this.form.reserveSet * 100,
            controlMonthWithdrawal: this.form.controlMonthWithdrawal * 100,
            password: this.form.passwordPlaintext
          })
          httpAction(url, data, 'post')
            .then(res => {
              if (res.code === 200) {
                this.$message.success(res.message)
                this.handleCancel()
                this.$emit('ok')
              } else {
                this.$message.error(res.message)
              }
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    validatePhone(rule, value, callback) {
      const reg1 = /^(?:(?:\d{3}-)?\d{8}|^(?:\d{4}-)?\d{7,8})(?:-\d+)?$/ // 电话号码
      const reg2 = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/ // 手机号
      if (reg1.test(value) || reg2.test(value)) {
        callback()
      } else {
        callback('请输入正确手机号码')
      }
    }
  }
}
</script>

<style scoped></style>

